package com.dx.financehy.modules.security.service;

import com.dx.financehy.utils.RedisUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Service
public class TaskService {

    private final StringRedisTemplate redisTemplate;
    private final ConcurrentHashMap<String, AtomicInteger> taskProgress = new ConcurrentHashMap<>();
    private final OnlineUserService onlineUserService;

    public TaskService(StringRedisTemplate redisTemplate, ObjectMapper objectMapper, RedisUtils redisUtils, OnlineUserService onlineUserService) {
        this.redisTemplate = redisTemplate;
        this.onlineUserService = onlineUserService;
    }

    @Async
    public void startTask(String taskId) throws Exception {
        log.info("主线程: {}", Thread.currentThread().getName());
        // 初始化任务进度为0
        taskProgress.put(taskId, new AtomicInteger(0));
        log.info("初始任务进度 (taskId: {}): {}", taskId, taskProgress.get(taskId));

        try {

            onlineUserService.testTask(taskProgress,taskId);

            log.info("完成任务 (taskId: {}) 在线程: {}", taskId, Thread.currentThread().getName());
        } catch (Exception e) {
            log.info("任务执行期间发生错误 (taskId: {}): {}", taskId, e.getMessage());
            taskProgress.remove(taskId);
            throw e;
        } finally {
            // 任务完成后移除进度（如果需要）
            // taskProgress.remove(taskId);
            log.info("移除任务进度 (taskId: {}) 在线程: {}", taskId, Thread.currentThread().getName());
        }
    }

    public int getProgress(String taskId) {
        log.info("获取任务进度 (taskId: {})", taskId);
        AtomicInteger progress = taskProgress.get(taskId);
        if (progress == null) {
            log.info("未找到任务进度 (taskId: {})", taskId);
            taskProgress.remove(taskId);
            return -1; // 如果任务不存在，返回-1
        }
        int currentProgress = progress.get();
        log.info("当前任务进度 (taskId: {}): {}%", taskId, currentProgress);
        return currentProgress;
    }

}
